package com.sinosoft.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.sinosoft.base.BaseFormController;
import com.sinosoft.base.Constants;
import com.sinosoft.orderinfo.OrderInfo;
import com.sinosoft.orderinfo.OrderInfoManager;
import com.sinosoft.orderinfomodel.OrderInfoModel;
import com.sinosoft.orderinfomodel.OrderInfoModelManager;
import com.sinosoft.product.ProductSearchManager;
import com.sinosoft.shopcar.ShopToOrderUtil;
import com.sinosoft.shopcar.ShopcarManager;
import com.sinosoft.shopcar.Shopinfo;
import com.sinosoft.shopcar.SwitchToShopcar;
import com.sinosoft.shopcar.SwitchToShopcarForAddshop;
import com.sinosoft.user.User;
import com.sinosoft.util.DisplayGetPage;
import com.sinosoft.util.PropertiesUtil;
import com.sinosoft.util.SystemConfigUtil;

@Controller
@RequestMapping("/shopcar/shopcar.html")
public class ShopCarController extends BaseFormController{
	ShopcarManager smgr;
	OrderInfoManager omgr;
//	CollectInfoManager cmgr;
	OrderInfoModelManager omodelmgr;
	ProductSearchManager productmgr;
	
	@Autowired
	public void setProductSearchManager(ProductSearchManager productmgr)
	{
		this.productmgr = productmgr;
	}
	
	@Autowired
	public void setShopcarManager(ShopcarManager smgr)
	{
		this.smgr = smgr;
	}
	
	@Autowired
	public void setOrderInfoManager(OrderInfoManager omgr)
	{
		this.omgr = omgr;
	}
	
//	@Autowired
//	public void setCollectModelManager(CollectInfoManager cmgr)
//	{
//		this.cmgr = cmgr;
//	}
	
	@Autowired
	public void setOrderInfoModelManager(OrderInfoModelManager omgr)
	{
		this.omodelmgr = omgr;
	}
	
	//修改保存购物车
	@RequestMapping(params="method=saveorupdate")
	public String saveProductOrder(Shopinfo shopinfo,HttpServletRequest request,HttpServletResponse response)
	{
		String page = request.getParameter("tz");
		String pagename = DisplayGetPage.getPageName("shopform", request);
		String savemodel = request.getParameter("savemodel");
		if ("".equalsIgnoreCase(page)) {
			page = "1";
		}
		//判断生产和产品订单
		String tasktype = request.getParameter("operate");
		BigDecimalConverter bd = new BigDecimalConverter(null);
		DateConverter dc = new DateConverter(null);
	    ConvertUtils.register(bd, java.math.BigDecimal.class);
	    ConvertUtils.register(dc, java.util.Date.class);
		int defa = 1;
		String username = SecurityUtils.getSubject().getPrincipal().toString();
		
		//读取用户默认模板
		OrderInfoModel om = omodelmgr.getOrderInfoModelByDefaultAndUsername(username, defa);
		if(om==null)
			om = new OrderInfoModel();
		if(tasktype.equals("1"))
		{
			om = changeOrderInfoModel(om, shopinfo);
		}
		else
		{
			om.setPriority(shopinfo.getPriority());
			om.setOrdermediumid(shopinfo.getOrdermediumid());
		}
		//判断页面保存模板的默认级别
		if(savemodel!=null)
		{
			om.setIsdefaulmodel(new BigDecimal(savemodel));
			if(savemodel.equals("2"))
			{
				if(om.getOrdermodelid()!=null)
					omodelmgr.updateInfoModel(om);
				else
					omodelmgr.saveOrderInfoModel(om);
			}
			else if(savemodel.equals("1"))
			{
				om.setIsdefaulmodel(new BigDecimal(2));
				om.setUserid(getUsername());
				om.setCreatetime(new Date());
				omodelmgr.saveOrderInfoModel(om);
			}
		}
		String op = request.getParameter("operate");
		if(op!=null && op.equals("production"))
		{
			Shopinfo oldshop = smgr.getShopinfoById(shopinfo.getOrderid().intValue());
			oldshop = ChangeShopinfo(oldshop,shopinfo);
			shopinfo = smgr.saveShopcar(oldshop);
			return "redirect:/shopcar/shopcar.html?method=query&" + pagename + "=" + page;
		}
		//获取一条购物车信息
		Shopinfo simodel = smgr.getShopinfoById(shopinfo.getOrderid().intValue());
		simodel.setPriority(shopinfo.getPriority());
		simodel.setOrdermediumid(shopinfo.getOrdermediumid());
		simodel.setBandsordered(shopinfo.getBandsordered());
		simodel.setReceivestationid(shopinfo.getReceivestationid());
		//保存购物车信息
		simodel = smgr.saveShopcar(simodel);
		
		return "redirect:/shopcar/shopcar.html?method=query&" + pagename + "=" + page;
	}
	
	//购物车列表信息
	@SuppressWarnings("unchecked")
	@RequestMapping(params="method=query")
	public ModelAndView searchlist(HttpServletRequest request,Model model)
	{
		List<Shopinfo> shopinfos = null;
		User user =  (User) request.getSession().getAttribute(Constants.LOCAL_USER);
		String username = user.getUsername();
		
		String page =  DisplayGetPage.getPageParamName("shopcars",request);//第几页
		if(page==null)
		{
			shopinfos = smgr.getShopcarList(username,0,Constants.pagesize);
		}
		else
		{
			shopinfos = smgr.getShopcarList(username,(Integer.parseInt(page)-1)*Constants.pagesize,Constants.pagesize);
		}
		String[] ordertypelist = PropertiesUtil.getPropertiesValue("shopcar.ordertypelist", request);
		Map<String,Object> ordertypemap = this.getMap(ordertypelist);
		model.addAttribute("ordertypelist",ordertypemap);
		String[] productlevellist = PropertiesUtil.getPropertiesValue("shopcar.productlevels", request);
		Map<String,Object> productlevelmap = this.getMap(productlevellist);
		model.addAttribute("productlevellist",productlevelmap);
		String[] producttypelist = PropertiesUtil.getPropertiesValue("ordermodel.producttypelist", request);
		Map<String,Object> producttypemap = this.getMap(producttypelist);
		model.addAttribute("producttypelist",producttypemap);
		
		int pageAll = 0;
		pageAll = smgr.getShopcarCount(username);
		model.addAttribute("resultSize", pageAll);
		model.addAttribute("pagesize",Constants.pagesize);
		double size = pageAll;
		model.addAttribute("displayallpage", Math.ceil(size / Constants.pagesize));
		model.addAttribute("thispage", Integer.parseInt(page));
		return new ModelAndView("shopcar/shopcarlist",Constants.SHOPCAR_LIST,shopinfos);
	}
	
	//查看购物车 
	@SuppressWarnings("unchecked")
	@RequestMapping(params="method=view")
	public String showShopinfo(HttpServletRequest request,@RequestParam(required=true,value="orderid")String orderid,ModelMap model)
	{
		Shopinfo shopinfo = null;
		if(orderid!=null && !"".equals(orderid))
		{
			shopinfo = smgr.getShopinfoById(Integer.parseInt(orderid));
		}
		else
		{
			shopinfo =new Shopinfo();
		}
		model.addAttribute("shopinfo",shopinfo);
		String[] ordertypelist = PropertiesUtil.getPropertiesValue("shopcar.ordertypelist", request);
		Map<String,Object> ordermap = this.getMap(ordertypelist);
		model.addAttribute("ordermap",ordermap);
		String[] prioritylist = PropertiesUtil.getPropertiesValue("shopcar.prioritylist", request);
		Map<String,Object> prioritymap = this.getMap(prioritylist);
		model.addAttribute("prioritymap",prioritymap);
		String[] ordermediumidlist = PropertiesUtil.getPropertiesValue("shopcar.ordermediumidlist", request);
		Map<String,Object> ordermediumidmap = this.getMap(ordermediumidlist);
		model.addAttribute("ordermediumidmap",ordermediumidmap);
		return "shopcar/viewshopcar";
	}
	
	//删除购物车
	@RequestMapping(params="method=delete")
	public String saveShopcar(HttpServletRequest request,HttpServletResponse response)
	{
		String page = request.getParameter("tz");
		String pagename = DisplayGetPage.getPageName("shopcars", request);
//		String postmethod = request.getParameter("ptmeth");
		if ("".equalsIgnoreCase(page)) {
			page = "1";
		}
		if(isDelete(request)){
			String orderid = request.getParameter("id");
			if(orderid!=null && !"".equals(orderid))
			{
				smgr.removeShopcar(orderid);
			}
		}
		
//		if ("select".equalsIgnoreCase(postmethod)) {
//			return "redirect:/shopcar/shopcar.html?method=query&"
//					+ pagename + "=" + page;
//		} else {
//			return "redirect:/shopcar/shopcar.html?method=query&"
//					+ pagename + "=" + page;
//		}
		return "redirect:/shopcar/shopcar.html?method=query&"
		+ pagename + "=" + page;
//		return "redirect:/shopcar/shopcar.html?method=query";
	}
	
	//购物车提交
	@RequestMapping(params="method=commit")
	public String commit(HttpServletRequest request,HttpServletResponse response)
	{
		User user = (User) request.getSession().getAttribute(Constants.LOCAL_USER);
		
		String ftpurl = null;
		//FTP地址
		String url = user.getFtpurl();
		if(url!=null)
		{
			if(url.indexOf(".")!=-1)
				ftpurl = "ftp://" + user.getUsername() + ":" + user.getPassword() + "@"+url + ":" + user.getFtpport() +"/";
			else
				ftpurl = "file://"+url;
		}
		Date date = new Date();
		String[] orderids = request.getParameterValues("ordername");
		String ids = "-1";
		for (int i = 0; i < orderids.length; i++) {
			ids += "," + orderids[i];
		}
		List<Shopinfo> shopinfos = smgr.getShopinfoListByIds(ids);
		List<OrderInfo> orderlist = new ArrayList<OrderInfo>();
//		List<CollectInfo> collectlist = new ArrayList<CollectInfo>();
		for (Shopinfo s : shopinfos) {
//			if(s.getTasktype().toString().equals("3"))//采集单
//			{
//				CollectInfo c = ShopToCollectUtil.switchcollectinfo(s);
//				collectlist.add(c);
//			}
//			else//生产订单或者普通订单
//			{
				OrderInfo o = ShopToOrderUtil.switchOrderInfo(s,ftpurl);
				orderlist.add(o);
//			}
		}
		String[] checkrules = SystemConfigUtil.getSystemValue("orderflag", this.getServletContext());
		for (OrderInfo o : orderlist) {
			if(null!=checkrules)
			{
				String satesensor = o.getSatelliteid()+"_"+o.getSensorid();
				int isboo=0;
				for (int i = 0; i < checkrules.length; i++) {
					if(satesensor.equals(checkrules[i]))
					{
						isboo = 1;
						o.setAreadystate(new BigDecimal(1));//符合需要审核的规则，订单状态为等待审核
					}
				}
				if(isboo!=1)
				{
					o.setAreadystate(new BigDecimal(2));//订单的卫星和传感器都不符合审核的规则，订单状态为审核通过
					o.setChecktime(date);
				}
			}
			else
			{
				o.setOrderstate(new BigDecimal(2));//没有审核规则，订单状态为审核通过
				o.setChecktime(date);
			}
			o.setIssend(0);
			o.setIscountclose(0);
			o.setOrderstate(new BigDecimal(4));
			o.setTasktime(date);
			omgr.saveOrderInfo(o);
		}
//		for (CollectInfo c : collectlist) {
//			
//			User localuser = (User)request.getSession().getAttribute(Constants.LOCAL_USER);
//			c.setTaskid(cmgr.getSequence());
//			
//			c.setTaskStatus("default");
//			c.setIscancel(BigDecimal.valueOf(0));
//			c.setIssend(BigDecimal.valueOf(0));
//			c.setUsertype(localuser.getUsertype());//此处需要通过用户名来拿到用户类型
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			Date dd = Calendar.getInstance().getTime();
//			c.setSubdate(DateTimeUtils.StringToDate(sdf.format(dd),
//					"yyyy-MM-dd HH:mm:ss"));
//			cmgr.saveCollectInfo(c);
//		}
		smgr.removeShopcarlist(shopinfos);
		return "redirect:/shopcar/shopcar.html?method=query";
	}
	
	//加入购物车保存方法
	@RequestMapping(params="method=productsave")
	public String saveShopcarByProduct(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String productLevel = request.getParameter("productLevel");
		String products = request.getParameter("products");
		String modelname = productLevel;
		String isProduceOrder = request.getParameter("isProduceOrder");
		if(isProduceOrder.equalsIgnoreCase("YES"))//生产订单查询0级Model
			modelname = Constants.LEVEL_0_MODEL;
		//转换级别
		String level = productLevel.toUpperCase();
		level = level.replace("ZYWXIMAGE", "LEVEL");
		
		List<Object> objlist = productmgr.getProducts(modelname, products);
		List<Shopinfo> shopinfolist = new ArrayList<Shopinfo>();
		//查询默认模版
		shopinfolist = SwitchToShopcarForAddshop.getShopinfo(objlist,omodelmgr,isProduceOrder,level);
		User localuser = (User)request.getSession().getAttribute(Constants.LOCAL_USER);
		if(isProduceOrder.equalsIgnoreCase("YES"))
		{
			for (int i = 0; i < shopinfolist.size(); i++) {
				Shopinfo s = shopinfolist.get(i);
				s.setProductlevel(level);
				s.setUsertype(localuser.getUsertype());
			}
		}
		else
		{
			for (int i = 0; i < shopinfolist.size(); i++) {
				Shopinfo s = shopinfolist.get(i);
				s.setUsertype(localuser.getUsertype());
			}
		}
		
		String jsonstr = smgr.SaveShopcarList(shopinfolist);
		response.setContentType("applicate/json");
        PrintWriter out = response.getWriter();
        out.write(jsonstr);
        out.flush();
        out.close();
		return null;
	}
	
	//添加高级产品到购物车
	@RequestMapping(params="method=highproductsave")
	public ModelAndView highProductAdddtoShopcar(HttpServletRequest request,HttpServletResponse response) throws Exception
	{
		String productLevel = request.getParameter("productLevel");
		String products = request.getParameter("products");
		String mapnumber = request.getParameter("mapNumber");//图幅号
		String productids = "";
		if(products!=null&&!products.equals(""))
		{
			String[] satesenproductid = products.split(",");
			for (int i = 0; i < satesenproductid.length; i++) {
				String tempstr = satesenproductid[i].toString();
				String[] productstrs = tempstr.split("_");
				if(productstrs.length>3)
				{
					String productstr = productstrs[2].toString();
					if(!productids.isEmpty())
						productids += ","+productstr;
					else
						productids += productstr;
				}
			}
		}
		//转换级别
		String level = productLevel.toUpperCase();
		level = level.replace("ZYWXIMAGEHIGH", "");
		
		String modelname = productLevel;
		String isProduceOrder = request.getParameter("isProduceOrder");
		if(isProduceOrder.equalsIgnoreCase("YES"))//判断是否生产订单YES是
		{
			if(level.equals(Constants.LEVEL_SDEM))
				modelname = Constants.LEVEL_DEM_MODEL;
			else
				modelname = Constants.LEVEL_DOM_MODEL;
		}
			
		
		
		List<Object> objlist = productmgr.getProducts(modelname, products);
		List<Shopinfo> shopinfolist = new ArrayList<Shopinfo>();
		//查询默认模版
		shopinfolist = SwitchToShopcar.getHighShopinfo(objlist,omodelmgr,isProduceOrder,mapnumber);
		User localuser = (User)request.getSession().getAttribute(Constants.LOCAL_USER);
		if(isProduceOrder.equalsIgnoreCase("YES"))
		{
			for (int i = 0; i < shopinfolist.size(); i++) {
				Shopinfo s = shopinfolist.get(i);
				s.setProductlevel(level);
				s.setUsertype(localuser.getUsertype());
			}
		}
		else
		{
			for (int i = 0; i < shopinfolist.size(); i++) {
				Shopinfo s = shopinfolist.get(i);
				s.setUsertype(localuser.getUsertype());
				s.setMapsheetname(productids);
			}
		}
		
		String jsonstr = smgr.SaveShopcarList(shopinfolist);
		response.setContentType("applicate/json");
        PrintWriter out = response.getWriter();
        out.write(jsonstr);
        out.flush();
        out.close();
		return null;
	}
	
	//清空购物车
	@RequestMapping(params="method=clear")
	public String clearAll(HttpServletRequest request,HttpServletResponse response)
	{
		String username = SecurityUtils.getSubject().getPrincipal().toString();
		List<Shopinfo> shopinfos = smgr.getShopcarListByUsername(username,null);
		smgr.removeShopcarlist(shopinfos);
		return "redirect:/shopcar/shopcar.html?method=query";
	}

	/**
	 * 购物车修改
	 * @param id
	 * @param modelmap
	 * @param model
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params="method=form")
	public String updateProductOrder(@RequestParam(required=true,value="id")String id,ModelMap modelmap,Model model,HttpServletRequest request)
	{
		String[] prioritylist = PropertiesUtil.getPropertiesValue("shopcar.prioritylist",request);//读取优先级
		Map<String, Object> prioitymap = getMap(prioritylist);
		model.addAttribute("prioitymap", prioitymap);
		Shopinfo shopinfo = smgr.getShopinfoById(Integer.parseInt(id));
		String receivestationlist = shopinfo.getReceivestationid();
		if(receivestationlist!=null)
		{
			String[] receives = receivestationlist.split(",");
			model.addAttribute("receives",receives);
		}
		modelmap.addAttribute("shopinfo",shopinfo);
		String page = request.getParameter("tz");
		String pagename = DisplayGetPage.getPageName("shopform", request);
		model.addAttribute("tzpage", page);
		model.addAttribute("pagename", pagename);
		if(shopinfo!=null && shopinfo.getTasktype()!=null)
		{
			if(shopinfo.getTasktype().intValue()==3)//采集单
			{
				String[] satellitelist = SystemConfigUtil.getSystemValue("satellite", this.getServletContext());//读取卫星
				model.addAttribute("satellitelist",satellitelist);
				Map<String,Object> map = new HashMap<String, Object>();
				//读取传感器
				for (int i = 0; i < satellitelist.length; i++) {
					String[] sensorlist = SystemConfigUtil.getSystemValue(satellitelist[i], this.getServletContext());//传感器
					if(sensorlist!=null && !sensorlist[0].equals(""))
						map.put(satellitelist[i],sensorlist);
				}
				model.addAttribute("map",map);
				String[] receivestationidlist = SystemConfigUtil.getSystemValue("receivestationid", this.getServletContext());
				model.addAttribute("receivestationidlist",receivestationidlist);
				model.addAttribute("form","collect");
				//接收站
				String[] receivingstations = SystemConfigUtil.getSystemValue("receivingstation", this.getServletContext());
				model.addAttribute("receivingstation",receivingstations);
				if(shopinfo.getReceivestationid()!=null)
					model.addAttribute("mers", shopinfo.getReceivestationid().split(","));
			}
			else if(shopinfo.getTasktype().intValue()==1)//生产订单
			{
				//产品级别
				String[] heighmodelist = SystemConfigUtil.getSystemValue("heighmodelist", this.getServletContext());
				String[] satellitelist = SystemConfigUtil.getSystemValue("satellite", this.getServletContext());
				String[] attitudedatalist = SystemConfigUtil.getSystemValue("attitudedata", this.getServletContext());
				String[] demtypelist = SystemConfigUtil.getSystemValue("demtype", this.getServletContext());
				String[] orthographmethodlist = SystemConfigUtil.getSystemValue("orthographmethod", this.getServletContext());
				String[] geodeticmethodlist = SystemConfigUtil.getSystemValue("geodeticmethod", this.getServletContext());
				String[] equationorderlist = SystemConfigUtil.getSystemValue("equationorder", this.getServletContext());
				String[] pgproductformatlist = SystemConfigUtil.getSystemValue("pgproductformat", this.getServletContext());
				String[] mapprojectionlist = SystemConfigUtil.getSystemValue("mapprojection", this.getServletContext());
				String[] weightazimuthlist = SystemConfigUtil.getSystemValue("weightazimuth", this.getServletContext());
				String[] rangelookslist = SystemConfigUtil.getSystemValue("rangelookslist", this.getServletContext());
				String[] weightrangelist = SystemConfigUtil.getSystemValue("weightrange", this.getServletContext());
				String[] reconstructprocsslist = SystemConfigUtil.getSystemValue("reconstructprocss", this.getServletContext());
				String[] addwindowlist = SystemConfigUtil.getSystemValue("addwindow", this.getServletContext());
				String[] correctphaselist = SystemConfigUtil.getSystemValue("correctphaselist", this.getServletContext());
				String[] earthmodellist = SystemConfigUtil.getSystemValue("earthmodellist", this.getServletContext());
				String[] datatypelist = SystemConfigUtil.getSystemValue("datatypelist", this.getServletContext());
				String[] resamplingkernellist = SystemConfigUtil.getSystemValue("resamplingkernel", this.getServletContext());
				String[] productorientationlist = SystemConfigUtil.getSystemValue("productorientation", this.getServletContext());
				String[] azimuthlookslist = PropertiesUtil.getPropertiesValue("shopcar.azimuthlookslist", request);
				String[] mapzonetypelist = SystemConfigUtil.getSystemValue("mapzonetype", this.getServletContext());
				model.addAttribute("mapzonetypelist",mapzonetypelist);
				//是否去噪
				String[] denoiseslist = PropertiesUtil.getPropertiesValue("ordermodel.denoises", request);
				Map<String,Object> denoisesmap = new HashMap<String, Object>();
				denoisesmap = this.getMap(denoiseslist);
				model.addAttribute("denoisesmap",denoisesmap);
				//MTF补偿
				String[] mtftypelist = PropertiesUtil.getPropertiesValue("ordermodel.mtftypes", request);
				Map<String,Object> mtftypemap = new HashMap<String, Object>();
				mtftypemap = this.getMap(mtftypelist);
				model.addAttribute("mtftypelist",mtftypemap);
				//辐射校正方法
				String[] radiometricmethodlist = PropertiesUtil.getPropertiesValue("ordermodel.mtftypes", request);
				Map<String,Object> radiometricmethodmap = new HashMap<String, Object>();
				radiometricmethodmap = this.getMap(radiometricmethodlist);
				model.addAttribute("radiometricmethodmap",radiometricmethodmap);
				//接收站
				String[] receivestationidlist = PropertiesUtil.getPropertiesValue("ordermodel.receivestationids", request);
				Map<String,Object> receivestationidmap = new HashMap<String, Object>();
				receivestationidmap = this.getMap(receivestationidlist);
				model.addAttribute("receivestationidmap",receivestationidmap);
				//瑞利散射
				String[] rayleighcorrectionlist = SystemConfigUtil.getSystemValue("rayleighcorrections", this.getServletContext());
				model.addAttribute("rayleighcorrectionlist",rayleighcorrectionlist);
				
				String[] earthellipsoidlist = SystemConfigUtil.getSystemValue("earthellipsoid", this.getServletContext());
				model.addAttribute("earthellipsoidlist",earthellipsoidlist);
								
				//读取资源文件内容
				//1、结算方式
				Map<String,Object> clearmap = new HashMap<String, Object>();
				String[] clearformlist = PropertiesUtil.getPropertiesValue("ordermodel.clearformvalue", request);
				clearmap = this.getMap(clearformlist);
				model.addAttribute("clearform",clearmap);
				//2、订购介质
				Map<String,Object> mediummap = new HashMap<String, Object>();
				String[] mediumlist = PropertiesUtil.getPropertiesValue("shopcar.ordermediumidlist", request);
				mediummap = this.getMap(mediumlist);
				model.addAttribute("medium",mediummap);
				//4、坐标系
				Map<String,Object> coordtypemap = new HashMap<String, Object>();
				String[] coordtypelist = PropertiesUtil.getPropertiesValue("ordermodel.coordtypelist", request);
				coordtypemap = this.getMap(coordtypelist);
				model.addAttribute("coordtypelist",coordtypemap);
				//5、产品类型
				Map<String,Object> producttypemap = new HashMap<String, Object>();
				String[] producttypelist = PropertiesUtil.getPropertiesValue("ordermodel.producttypelist", request);
				producttypemap = this.getMap(producttypelist);
				model.addAttribute("producttypelist",producttypemap);
				//6、多普勒质心计算方法
				Map<String,Object> fdcmap = new HashMap<String, Object>();
				String[] fdclist = PropertiesUtil.getPropertiesValue("ordermodel.fdclist", request);
				fdcmap = this.getMap(fdclist);
				model.addAttribute("fdclist",fdcmap);
				//7、多普勒频率计算方法
				Map<String,Object> fdrmap = new HashMap<String, Object>();
				String[] fdrlist = PropertiesUtil.getPropertiesValue("ordermodel.fdrlist", request);
				fdrmap = this.getMap(fdrlist);
				model.addAttribute("fdrlist",fdrmap);
				//8、天线方向图数据来源 
				Map<String,Object> antenmap = new HashMap<String, Object>();
				String[] antenlist = PropertiesUtil.getPropertiesValue("ordermodel.antenlist", request);
				antenmap = this.getMap(antenlist);
				model.addAttribute("antenlist",antenmap);
				//9、任务类型
				Map<String,Object> tasktypemap = new HashMap<String, Object>();
				String[] tasktypelist = PropertiesUtil.getPropertiesValue("shopcar.ordertypelist", request);
				tasktypemap = this.getMap(tasktypelist);
				model.addAttribute("tasktypelist",tasktypemap);
				
				//5、轨道类型
				Map<String,Object> orbittypemap = new HashMap<String, Object>();
				String[] orbittypelist = PropertiesUtil.getPropertiesValue("ordermodel.orbittypelist", request);
				orbittypemap = this.getMap(orbittypelist);
				model.addAttribute("orbittypelist",orbittypemap);
				
				
				//10、姿态类型
				Map<String,Object> atttypemap = new HashMap<String, Object>();
				String[] atttypelist = PropertiesUtil.getPropertiesValue("ordermodel.atttypelist", request);
				atttypemap = this.getMap(atttypelist);
				model.addAttribute("atttypemap",atttypemap);
				
				//11、自适应生产方式
				String[] autoprocessinglist = SystemConfigUtil.getSystemValue("autoprocessinglist", this.getServletContext());
				model.addAttribute("autoprocessinglist", autoprocessinglist);
				
				//12、波段配准
				Map<String,Object> bandregistermap = new HashMap<String,Object>();
				String[] bandregisterlist = PropertiesUtil.getPropertiesValue("ordermodel.bandregisterlist", request);
				bandregistermap = this.getMap(bandregisterlist);
				model.addAttribute("bandregistermap", bandregistermap);
				
				//13、片间均衡
				String[] ccdbalancelist = SystemConfigUtil.getSystemValue("ccdbalancelist", this.getServletContext());
				model.addAttribute("ccdbalancelist", ccdbalancelist);
				
				//13、DEM来源
				String[] demsourcelist = SystemConfigUtil.getSystemValue("demsourcelist", this.getServletContext());
				model.addAttribute("demsourcelist", demsourcelist);
				
				//13、控制点来源
				String[] gcpsourcelist = SystemConfigUtil.getSystemValue("gcpsourcelist", this.getServletContext());
				model.addAttribute("gcpsourcelist", gcpsourcelist);
				
				//14、轨道参数
				Map<String,Object> ephemerisdatamap = new HashMap<String, Object>();
				String[] ephemerisdatalist = PropertiesUtil.getPropertiesValue("shopcar.ephemerisdatas", request);
				ephemerisdatamap = this.getMap(ephemerisdatalist);
				model.addAttribute("ephemerisdatamap",ephemerisdatamap);
				
				//14、姿态参数
				Map<String,Object> attitudedatasmap = new HashMap<String, Object>();
				String[] attitudedataslist = PropertiesUtil.getPropertiesValue("ordermodel.attitudedatas", request);
				attitudedatasmap = this.getMap(attitudedataslist);
				model.addAttribute("attitudedatasmap",attitudedatasmap);
				
				//产品级别
				String[] productlevels = PropertiesUtil.getPropertiesValue("shopcar.productlevels", request);
				Map<String,Object> productlevelsmap = getMap(productlevels);
				model.addAttribute("productlevelsmap", productlevelsmap);
				
				Map<String,Object> azimuthlooksmap = new HashMap<String, Object>();
				azimuthlooksmap = this.getMap(azimuthlookslist);
				model.addAttribute("azimuthlookslist",azimuthlooksmap);
				
				model.addAttribute("heighmodelist",heighmodelist);
				model.addAttribute("satellitelist",satellitelist);
				model.addAttribute("attitudedatalist",attitudedatalist);
				model.addAttribute("demtypelist",demtypelist);
				model.addAttribute("orthographmethodlist",orthographmethodlist);
				model.addAttribute("geodeticmethodlist",geodeticmethodlist);
				model.addAttribute("equationorderlist",equationorderlist);
				model.addAttribute("pgproductformatlist",pgproductformatlist);
				model.addAttribute("mapprojectionlist",mapprojectionlist);
				model.addAttribute("weightazimuthlist",weightazimuthlist);
				model.addAttribute("correctphaselist",correctphaselist);
				model.addAttribute("rangelookslist",rangelookslist);
				model.addAttribute("weightrangelist",weightrangelist);
				model.addAttribute("reconstructprocsslist",reconstructprocsslist);
				model.addAttribute("addwindowlist",addwindowlist);
				model.addAttribute("earthmodellist",earthmodellist);
				model.addAttribute("datatypelist",datatypelist);
				model.addAttribute("resamplingkernellist",resamplingkernellist);
				model.addAttribute("productorientationlist",productorientationlist);
				
				
				model.addAttribute("operate","production");
				return "shopcar/productshopcar";
				
			}
			else//产品订单
			{
				String[] bandsorderedlist = SystemConfigUtil.getSystemValue("bandsordered", this.getServletContext());
				String[] ordermediumidlist = PropertiesUtil.getPropertiesValue("shopcar.ordermediumidlist",request);
				Map<String, Object> ordermediumidmap = this.getMap(ordermediumidlist);
				model.addAttribute("bandsorderedlist", bandsorderedlist);
				
				model.addAttribute("ordermediumidmap", ordermediumidmap);
				model.addAttribute("form","product");
			}
			
		}
		
		return "shopcar/shopcarform";
	}
	
	/**
	 * 采集单的修改
	 * @param shopinfo
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=collect")
	public String updateCollect(Shopinfo shopinfo,HttpServletRequest request,HttpServletResponse response)
	{
		Shopinfo sinfo = smgr.getShopinfoById(shopinfo.getOrderid().intValue());
		String leftup = request.getParameter("leftup");
		String[] leftups = getStringList(leftup,",");
		if(leftups!=null)
		{
			sinfo.setUpperleftlong(Double.parseDouble(leftups[0]));
			sinfo.setUpperleftlat(Double.parseDouble(leftups[1]));
		}
		String rightup = request.getParameter("rightup");
		String[] rightups = getStringList(rightup,",");
		if(rightups!=null)
		{
			sinfo.setUpperrightlong(Double.parseDouble(rightups[0]));
			sinfo.setUpperleftlat(Double.parseDouble(rightups[1]));
		}
		String leftdown = request.getParameter("leftdown");
		String[] leftdowns = getStringList(leftdown,",");
		if(leftdowns!=null)
		{
			sinfo.setLowerleftlong(Double.parseDouble(leftdowns[0]));
			sinfo.setLowerleftlat(Double.parseDouble(leftdowns[1]));
		}
		String rightdown = request.getParameter("rightdown");
		String[] rightdowns = getStringList(rightdown,",");
		if(rightdowns!=null)
		{
			sinfo.setLowerrightlong(Double.parseDouble(rightdowns[0]));
			sinfo.setLowerrightlat(Double.parseDouble(rightdowns[1]));
		}
//		String sensorids = request.getParameter("sensorid");
		sinfo.setSensorid(shopinfo.getSensorid());
		sinfo.setReceivestationid(shopinfo.getReceivestationid());
		sinfo.setPriority(shopinfo.getPriority());
		//卫星
		Map<String,Object> satemap = new HashMap<String, Object>();
		if(shopinfo.getSensorid()!=null)
		{
			String[] sensors = {};
			sensors = shopinfo.getSensorid().split(",");
			for (int i = 0; i < sensors.length; i++) {
				String[] satesen = sensors[i].split("_");
				satemap.put(satesen[0], satesen[1]);
			}
		}
			
		Set<String> set = satemap.keySet();
		Iterator it = set.iterator();
		String sates = null;
		while(it.hasNext())
		{
			if(sates==null)
				sates = it.next() + "";
			else
				sates += "," + it.next();
		}
		sinfo.setSatelliteid(sates);
		shopinfo = smgr.saveShopcar(sinfo);
		return "redirect:/shopcar/shopcar.html?method=query";
	}
	
	/**
	 * 购物车覆盖页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="method=cover")
	public String shopcarover(HttpServletRequest request,HttpServletResponse response,Model model)
	{
		String[] orderids = request.getParameterValues("orderid");
		String ids = "";
		for (int i = 0; i < orderids.length; i++) {
			if(!ids.isEmpty())
			{
				ids += "," + orderids[i];
			}
			else
			{
				ids = orderids[i];
			}
		}
		/*保存选择的购物车信息*/
		if(request.getSession().getAttribute("orderid")!=null)
		{
			request.getSession().removeAttribute("orderid");
		}
		request.getSession().setAttribute("orderid", ids);
		model.addAttribute("orderids",ids);
		String viewmethod = request.getParameter("viewmethod");
		if(viewmethod!=null && !viewmethod.isEmpty() && viewmethod.equals("shopcar"))
//			return "shopcar/shopcarCover";
			return "shopcar/shopcarCover";
		else
			return "orderinfo/orderinfoCover";
	}
	
	// 购物车覆盖操作
	@RequestMapping(params = "method=shopcarCoverajax")
	public ModelAndView collectCoverPro(HttpServletRequest request,
			HttpServletResponse response) {
		Object orderidobj = request.getSession().getAttribute("orderid");
		String orderid = null;
		if(orderidobj!=null && !"".equals(orderidobj))
			orderid = orderidobj.toString();
		String username = SecurityUtils.getSubject().getPrincipal().toString();
		List<Shopinfo> shopcarlist = smgr.getShopcarListByUsername(username,orderid);
		JSONObject jsonObj = new JSONObject();

//		Map<String, String[]> ingredients = new HashMap<String, String[]>();
		ArrayList list = new ArrayList();
		for (int i = 0; i < shopcarlist.size(); i++) {
			Shopinfo shop = shopcarlist.get(i);
			String[] point = { shop.getUpperleftlong().toString(),
					shop.getUpperleftlat().toString(),
					shop.getUpperrightlong().toString(),
					shop.getUpperrightlat().toString(),
					shop.getLowerrightlong().toString(),
					shop.getLowerrightlat().toString(),
					shop.getLowerleftlong().toString(),
					shop.getLowerleftlat().toString() 
					};
			list.add(point);
//			ingredients.put("str"+i, point);
		}

		// 返回一个JSONArray对象
		jsonObj.put("ingredients", list);

		try {
			response.getWriter().write(jsonObj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	// 订单覆盖操作
	@RequestMapping(params = "method=orderCoverajax")
	public ModelAndView orderCoverPro(HttpServletRequest request,
			HttpServletResponse response) {
		Object orderidobj = request.getSession().getAttribute("orderids");
		String orderid = null;
		if(orderidobj!=null && !"".equals(orderidobj))
			orderid = orderidobj.toString();
		String username = SecurityUtils.getSubject().getPrincipal().toString();
		List<OrderInfo> orderlist = omgr.getOrderinfoListByUsername(username,orderid);
		JSONObject jsonObj = new JSONObject();
//		Map<String, String[]> ingredients = new HashMap<String, String[]>();
		ArrayList list = new ArrayList();
		for (int i = 0; i < orderlist.size(); i++) {
			OrderInfo order = orderlist.get(i);
			String[] point = { order.getUpperleftlong().toString(),
					order.getUpperleftlat().toString(),
					order.getUpperrightlong().toString(),
					order.getUpperrightlat().toString(),
					order.getLowerrightlong().toString(),
					order.getLowerrightlat().toString(),
					order.getLowerleftlong().toString(),
					order.getLowerleftlat().toString() 
					};
			list.add(point);
//			ingredients.put("str"+i, point);
		}

		// 返回一个JSONArray对象
		jsonObj.put("ingredients", list);

		try {
			response.getWriter().write(jsonObj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;

	}
	
	//获取传感器的方法
	@RequestMapping(params = "method=satellite",method = RequestMethod.POST)        
	public ModelAndView satellite(String sensorlist,HttpServletRequest request,HttpServletResponse response) {  
		String json =  "{\"name\":\"zywx\"}";
	    JSONObject jsonObj = JSONObject.fromObject(json); 
		Map <String, String> ingredients = new HashMap <String, String>(); 
		if(sensorlist!=null)
		{
			String [] sensors = sensorlist.split(",");
			for(int i = 0;i < sensors.length ; i++){
		    	ingredients.put("str"+i, sensors[i].toString()); 
		    }
			jsonObj.put("ingredients",ingredients);
			
		    try { 
		        response.getWriter().write(jsonObj.toString()); 
		    } catch (IOException e) { 
		        e.printStackTrace(); 
		    }
		}
	      
	    return null;
    }
	
	//判断添加
	public boolean isAdd(HttpServletRequest request)
	{
		String method = request.getParameter("operate");
        return (method != null && method.equalsIgnoreCase("add"));
	}
	
	//判断更新
	public boolean isUpdate(HttpServletRequest request)
	{
		String method = request.getParameter("operate");
        return (method != null && method.equalsIgnoreCase("update"));
	}
	
	//判断删除
	public boolean isDelete(HttpServletRequest request)
	{
		String method = request.getParameter("operate");
        return (method != null && method.equalsIgnoreCase("delete"));
	}
	
	//解析str,str1返回string[]
	public String[] getStringList(String values,String splits)
	{
		String[] returns = values.split(splits);
		if(returns!=null && returns.length>1 && returns[0]!=null && !"".equals(returns[0]) && returns[1]!=null && !"".equals(returns[1]))
		{
			return returns;
		}
		else
		{
			return null;
		}
	}
	
	
	
	//解析String[]返回map
	@SuppressWarnings("unchecked")
	public Map getMap(String[] str)
	{
		Map<String,Object> map = new HashMap<String, Object>();
		for (int i = 0; i < str.length; i++) {
			String[] obj = str[i].split("_");
			if(obj.length>1)
				map.put(obj[1], obj[0]);
			else
				map.put(obj[0], obj[0]);
		}
		return map;
	}
	
	public Shopinfo ChangeShopinfo(Shopinfo oldshop,Shopinfo shopinfo)
	{
//		oldshop.setordermodelid;
//		oldshop.setuserid;
//		oldshop.setCreatetime(createtime);
		oldshop.setPriority(shopinfo.getPriority());
//		oldshop.setSatelliteid(shopinfo.getSatelliteid());
//		oldshop.setSensorid(shopinfo.getSensorid());
		oldshop.setOrdermediumid(shopinfo.getOrdermediumid());
		oldshop.setPgproductformat(shopinfo.getPgproductformat());
		oldshop.setProducttype(shopinfo.getProducttype());
		oldshop.setScenecount(shopinfo.getScenecount());
		oldshop.setSceneshift(shopinfo.getSceneshift());
		oldshop.setOrbittype(shopinfo.getOrbittype());
		oldshop.setAtttype(shopinfo.getAtttype());
		oldshop.setBandnumber(shopinfo.getBandnumber());
		oldshop.setImagegsd(shopinfo.getImagegsd());
		oldshop.setMapprojection(shopinfo.getMapprojection());
		oldshop.setEarthellipsoid(shopinfo.getEarthellipsoid());
		oldshop.setResamplingkernel(shopinfo.getResamplingkernel());
		oldshop.setHeightmode(shopinfo.getHeightmode());
		oldshop.setEphemerisdata(shopinfo.getEphemerisdata());
		oldshop.setAttitudedata(shopinfo.getAttitudedata());
		oldshop.setRadiometricmethod(shopinfo.getRadiometricmethod());
		oldshop.setMtfcorrection(shopinfo.getMtfcorrection());
		oldshop.setDenoise(shopinfo.getDenoise());
		oldshop.setRayleighcorrection(shopinfo.getRayleighcorrection());
//		oldshop.setNote(shopinfo.getNote());
		oldshop.setClearform(shopinfo.getClearform());
		oldshop.setPixelspacing(shopinfo.getPixelspacing());
		oldshop.setOrthographmethod(shopinfo.getOrthographmethod());
		oldshop.setGeodeticmethod(shopinfo.getGeodeticmethod());
		oldshop.setEquationorder(shopinfo.getEquationorder());
		oldshop.setProductorientation(shopinfo.getProductorientation());
		oldshop.setEarthmodel(shopinfo.getEarthmodel());
		oldshop.setMtfcpromode(shopinfo.getMtfcpromode());
		oldshop.setDemtype(shopinfo.getDemtype());
		oldshop.setDatatype(shopinfo.getDatatype());
		oldshop.setCoordtype(shopinfo.getCoordtype());
		oldshop.setImagingalgor(shopinfo.getImagingalgor());
		oldshop.setFdcmethod(shopinfo.getFdcmethod());
		oldshop.setAzimuthlooks(shopinfo.getAzimuthlooks());
		oldshop.setRangelooks(shopinfo.getRangelooks());
		oldshop.setWeightrange(shopinfo.getWeightrange());
		oldshop.setDespecklemethod(shopinfo.getDespecklemethod());
		oldshop.setAntennapatternsource(shopinfo.getAntennapatternsource());
		oldshop.setAddwindow(shopinfo.getAddwindow());
		oldshop.setCorrectphase(shopinfo.getCorrectphase());
		oldshop.setReconstructprocss(shopinfo.getReconstructprocss());
		oldshop.setBandsordered(shopinfo.getBandsordered());
//		oldshop.setisdefaulmodel;
		oldshop.setWeightazimuth(shopinfo.getWeightazimuth());
		oldshop.setFdrmethod(shopinfo.getFdrmethod());
//		oldshop.setstarttime;
//		oldshop.setEndtime(endtime);
//		oldshop.setproductlevel;
		oldshop.setMapzonetype(shopinfo.getMapzonetype());
		oldshop.setGsd(shopinfo.getGsd());
		return oldshop;
	}
	
	//切换大写
	public String getUpperCase(String oldstr)
	{
		if(oldstr!=null && !oldstr.isEmpty())
			return oldstr.toUpperCase();
		else
			return null;
	}
	
	public OrderInfoModel changeOrderInfoModel(OrderInfoModel om,Shopinfo shop)
	{
		om.setPriority(shop.getPriority());
		om.setOrdermediumid(shop.getOrdermediumid());
		om.setPgproductformat(shop.getPgproductformat());
		om.setProducttype(shop.getProducttype());
		om.setScenecount(shop.getScenecount());
		om.setSceneshift(shop.getSceneshift());
		om.setOrbittype(shop.getOrbittype());
		om.setAtttype(shop.getAtttype());
		om.setBandnumber(shop.getBandnumber());
		om.setImagegsd(shop.getImagegsd());
		om.setMapprojection(shop.getMapprojection());
		om.setEarthellipsoid(shop.getEarthellipsoid());
		om.setResamplingkernel(shop.getResamplingkernel());
		om.setHeightmode(shop.getHeightmode());
		om.setEphemerisdata(shop.getEphemerisdata());
		om.setAttitudedata(shop.getAttitudedata());
		om.setRadiometricmethod(shop.getRadiometricmethod());
		om.setMtfcorrection(shop.getMtfcorrection());
		om.setDenoise(shop.getDenoise());
		om.setRayleighcorrection(shop.getRayleighcorrection());
		om.setNote(shop.getNote());
		om.setClearform(shop.getClearform());
		om.setPixelspacing(shop.getPixelspacing());
		om.setOrthographmethod(shop.getOrthographmethod());
		om.setGeodeticmethod(shop.getGeodeticmethod());
		om.setEquationorder(shop.getEquationorder());
		om.setProductorientation(shop.getProductorientation());
		om.setEarthmodel(shop.getEarthmodel());
		om.setMtfcpromode(shop.getMtfcpromode());
		om.setDemtype(shop.getDemtype());
		om.setDatatype(shop.getDatatype());
		om.setCoordtype(shop.getCoordtype());
		om.setImagingalgor(shop.getImagingalgor());
		om.setFdcmethod(shop.getFdcmethod());
		om.setAzimuthlooks(shop.getAzimuthlooks());
		om.setRangelooks(shop.getRangelooks());
		om.setWeightrange(shop.getWeightrange());
		om.setDespecklemethod(shop.getDespecklemethod());
		om.setAntennapatternsource(shop.getAntennapatternsource());
		om.setAddwindow(shop.getAddwindow());
		om.setCorrectphase(shop.getCorrectphase());
		om.setReconstructprocss(shop.getReconstructprocss());
		om.setBandsordered(shop.getBandsordered());
		om.setWeightazimuth(shop.getWeightazimuth());
		om.setFdrmethod(shop.getFdrmethod());
		om.setMapzonetype(shop.getMapzonetype());
		om.setGsd(shop.getGsd());
		om.setAutoprocessing(shop.getAutoprocessing());
		om.setBandregister(shop.getBandregister());
		om.setCcdbalance(shop.getCcdbalance());
		om.setDemsource(shop.getDemsource());
		om.setGcpsource(shop.getGcpsource());
		return om;
	}
}
